package com.eian.boot.common.core.excel.listener;

import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.event.AnalysisEventListener;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author alex.meng
 * @createDate 2025-09-24 21:42
 * @description Excel读取解析基础Listener
 **/
@Slf4j
@Getter
@NoArgsConstructor
public abstract class BaseExcelListener<T> extends AnalysisEventListener<T> {
    private static final int MAX_BATCH_SIZE = 2000;
    private final List<T> excelData = Lists.newArrayList();
    private final List<T> processFailData = Lists.newArrayList();
    private int sheetNo = 1;
    private int dataCount = 0;
    private int batchSize = 0;

    public BaseExcelListener(Integer batchSize) {
        this.batchSize = batchSize > MAX_BATCH_SIZE ? MAX_BATCH_SIZE : batchSize;
    }

    public BaseExcelListener(Integer batchSize, boolean customBatchSize) {
        this.batchSize = customBatchSize ? batchSize : MAX_BATCH_SIZE;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        excelData.add(t);
        dataCount++;
        if (batchSize > 0 && excelData.size() >= batchSize) {
            try {
                dataProcess(excelData);
            } catch (Exception e) {
                log.error("数据分片处理失败，数据大小：{}，数据：{}", excelData.size(), excelData, e);
                processFailData.addAll(excelData);
            }
            excelData.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("共读取完成 {} 个Sheet，当前共读取了 {} 条数据", sheetNo, dataCount);
        sheetNo++;
    }

    abstract protected void dataProcess(List<T> excelData);
}
